package com.wy.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 工具类
 */
public final class Tools {

	private static Logger log = Logger.getLogger(Tools.class.getName());
	
	/**
	 * T对象赋值给Map对象
	 * @param t 泛型对象
	 * @return Map
	 */
	public static <T> Map<String, Object> t2Map(T t){
		if(t == null){
			log.warning("this input 'T t' is null!!");
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try{
			Method[] methods = t.getClass().getDeclaredMethods();
			for(Method m : methods){
				String mName = m.getName();
				if(mName.contains("get") && !mName.equals("equals")
										 && !mName.equals("toString")
										 && !mName.equals("hashCode")){
					
					String key = firstChar2LowerCase(mName.substring(3));
					Object value = m.invoke(t);
					map.put(key, value);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return map;
	}
	/**
	 * Map对象赋值给泛型T对象
	 * @param cz Class<T>
	 * @param map Map
	 * @return T
	 */
	public static <T> T map2T(Class<T> cz, Map<String, Object> map){
		if(map == null || map.isEmpty()){
			log.warning("this input 'Map<String,Object> map' is null!!!");
			return null;
		}
		T t = null;;
		try {
			t = cz.newInstance();
			Method[] methods = cz.getDeclaredMethods();
			for(Method m : methods){
				String mName = m.getName();
				if(mName.contains("set") && !mName.equals("equals")
										 && !mName.equals("toString")
										 && !mName.equals("hashCode")){
					
					String key   = firstChar2LowerCase(mName.substring(3));
					m.invoke(t, map.get(key));
				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return t;
	}
	/**
	 * 字符串首字母转换为小写
	 * @param str
	 * @return
	 */
	public static String firstChar2LowerCase(String str){
		if(str == null || str.equals("")){
			log.warning("this input 'String str' is null!!!");
			return null;
		}
		String firstChar = str.substring(0,1);
		return str.replace(firstChar, firstChar.toLowerCase());
	}
	
	
}
